package com.front.web.lvyou_specialty_front;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.bootdo.common.redisUtils.JedisUtils;
import com.bootdo.common.redisUtils.ObjectUtils;
import com.bootdo.common.utils.*;
import com.bootdo.common.wxpay.*;
import com.bootdo.lvyou.domain.LvyouMember;
import com.bootdo.lvyou.domain.LvyouScenicTicketOrder;
import com.bootdo.lvyou.domain.XcxConfig;
import com.bootdo.lvyou_specialty.domain.*;
import com.bootdo.system.domain.UserDO;
import com.bootdo.wx.domain.Config;
import com.front.web.lvyou_specialty_front.pagevo.GoodsContentBodyVo;
import com.front.web.lvyou_specialty_front.pagevo.GoodsContentVo;
import com.front.web.lvyou_specialty_front.pagevo.GoodsOrderVo;
import com.front.web.lvyou_specialty_front.pagevo.TuikuanVo;
import com.front.web.lvyou_specialty_front.util.GoodsContentUtil;
import com.front.web.lvyou_specialty_front.util.OrderContentStatus;
import com.front.web.lvyou_specialty_front.util.SendMbMessageUtils;
import com.sun.prism.impl.shape.OpenPiscesRasterizer;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/f/orderAllController")
public class OrderAllFrontController extends LvyouSpecialtySuperController{

    private static final String WXPAYOK="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    private static final String WXPAYNO="<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[支付失败]]></return_msg></xml>";


    /*
    * 添加至购物车
    * 改变商品数量
    * 从购物车中删除商品
    * 获取购物车信息
    *
    *
    * 添加订单
    * 查看订单详情
    * 用户订单列表
    * 立即购买按钮
    *
    *
    * */

    /**
     * 将商品添加到购物车
     * http://localhost/f/orderAllController/addShopCart
     * @param uid， 用户的id
     * @param goodsId， 商品的id
     * @param operate， 要进行的操作，0代表减 1代表加
     * @param request
     * @return
     */
    @RequestMapping("addShopCart")
    public R addShopCart(@RequestParam(value = "uid", defaultValue = "0")Long uid,
                         @RequestParam(value = "goodsId", defaultValue = "0")Long goodsId,
                         @RequestParam(value = "operate",defaultValue = "-1") Integer operate,
                         @RequestParam(value = "count", defaultValue = "0")Integer count,
                         HttpServletRequest request) {


        if (uid == 0 || goodsId == 0 || count < 0) {
            return R.error("参数错误");
        }

        if (operate != 0 && operate != 1) {
            return R.error("参数错误");
        }


        // 得到用户信息
        LvyouMember nihaodamaMember = lvyouMemberService.get(uid);
        if (nihaodamaMember == null) {
            return R.error("用户信息不存在");
        }

        boolean isMember = false;

        List<GoodsContentVo> list = new ArrayList<>();
        // 得到商品信息
        LvyouSpecialtyProduct goods = lvyouSpecialtyProductService.get(goodsId);
        if (goods == null) {
            return R.error("商品信息错误");
        }

        // 得到用户信息
        String memberCartKey = DigestUtils.sha256Hex(nihaodamaMember.getMobile() + "qylyshop");

        try {

            // 针对map机型操作，然后set进redis，然后得到具体的钱数，然后返回
            boolean exists = JedisUtils.exists(memberCartKey);
            boolean isHaveGoods = false;
            Map<String, Object> map = new HashMap<>();
            if (exists) {

                // 判断此次的goodsid是否存在
                map = JedisUtils.getObjectMap(memberCartKey);
                if (map.containsKey(goodsId + "")) {
                    Integer oldNumber = (Integer) map.get(goodsId + "");
                    if (operate == 1) {

                        if (goods.getReportory() >= oldNumber + count) {
                            map.put("" + goodsId, oldNumber + count);
                            isHaveGoods = true;
                        } else {
                            return R.error("商品库存不足");
                        }

                    } else {
                        if (oldNumber - count > 0) {
                            map.put("" + goodsId, oldNumber - count);
                            isHaveGoods = true;
                        } else {
                            map.remove(goodsId + "");
                            isHaveGoods = true;
                        }
                    }
                } else {
                    if (operate == 1) {
                        if (goods.getReportory() - count >= 0) {
                            map.put("" + goodsId, count);
                            isHaveGoods = true;
                        }
                    } else {
                        return R.error("您的购物车不存在该商品");
                    }
                }
            } else {
                // 不存在就添加
                if (operate == 0) {
                    return R.error("您的购物车不存在该商品");
                } else {
                    if (goods.getReportory() - count >= 0) {
                        map.put("" + goodsId, count);
                        isHaveGoods = true;
                    } else {
                        return R.error("商品库存不足");
                    }
//                    map.put(goodsId + "", 1);
                }
            }
            if (map.isEmpty()) {
                JedisUtils.del(memberCartKey);
                return R.ok().put("l", new ArrayList<>(0)).put("totalFee", 0).put("allNumber",0).put("typeNumber", 0).put("isHaveGoods", false);
            }


            JedisUtils.setObjectMap(memberCartKey, map, 0);
            Map<String, Object> totalFeeAndGoods = getTotalFeeAndGoods(map, list, isMember);

            int goodsNumber = 0;
            if (map.containsKey("" + goodsId)) {
                goodsNumber = (Integer) map.get("" + goodsId);
            }

            int flag = 1;
            if (goods.getReportory() < goodsNumber) {
                flag = 0;
            }
            if (!isHaveGoods) {
                return R.error("库存不足");
            }
            // 当是有会员的相关操作时，就用这个
//            if (isMember) {
//                return R.ok().put("l", list).put("totalFee", totalFeeAndGoods.get("beginMoneyMember")).put("allNumber", totalFeeAndGoods.get("allNumber")).put("typeNumber", totalFeeAndGoods.get("typeNumber")).put("goodsNumber", goodsNumber).put("flag", flag).put("isHaveGoods", isHaveGoods);
//            } else {
//                return R.ok().put("l", list).put("totalFee", totalFeeAndGoods.get("beginMoney")).put("allNumber", totalFeeAndGoods.get("allNumber")).put("typeNumber", totalFeeAndGoods.get("typeNumber")).put("goodsNumber", goodsNumber).put("flag", flag).put("isHaveGoods", isHaveGoods);
//            }
            String hint = null;
            if (totalFeeAndGoods.get("underReportory") != null) {
                hint = "部分商品已超出库存最大值，已为您调整为最大库存";
                JedisUtils.setObjectMap(memberCartKey, map, 0);
            }
            return R.ok().put("l", list).put("totalFee", totalFeeAndGoods.get("beginMoney")).put("allNumber", totalFeeAndGoods.get("allNumber")).put("typeNumber", totalFeeAndGoods.get("typeNumber")).put("goodsNumber", goodsNumber).put("flag", flag).put("isHaveGoods", isHaveGoods).put("errHint", hint);

        } catch (Exception e) {
            e.printStackTrace();
            return R.error("添加失败");
        }
    }


    /**
     * 删除购物车的某一条商品信息
     * http://localhost/f/orderAllController/deleteCartGoods
     * @param uid
     * @param goodsId
     * @param request
     * @return
     */
    @RequestMapping("deleteCartGoods")
    public R deleteCartGoods(@RequestParam(value = "uid", defaultValue = "0")Long uid,
                             @RequestParam(value = "goodsId", defaultValue = "0")Long goodsId,
                             HttpServletRequest request) {

        // System.out.println("这是删除接口");
        if (uid == 0 || goodsId == 0) {
            return R.error("参数错误");
        }

        // 得到用户信息
        LvyouMember lvyouMember = lvyouMemberService.get(uid);
//        // 得到商品信息
//        NihaodamaMember user = (NihaodamaMember) request.getAttribute("user");
//
//        if (mid != user.getId()) {
//            return R.error("用户信息错误");
//        }

        List<GoodsContentBodyVo> resultList = new ArrayList<>();

        boolean isMember = false;
//        if (lvyouMember.getState() == 1) {
//            isMember = true;
//        }

        try {

            List<GoodsContentVo> list = new ArrayList<>();
            String memberCartKey = DigestUtils.sha256Hex(lvyouMember.getMobile() + "qylyshop");
            boolean exists = JedisUtils.exists(memberCartKey);
            if (exists) {

                Map<String, Object> objectMap = JedisUtils.getObjectMap(memberCartKey);
                if (objectMap.containsKey(goodsId + "")) {
                    objectMap.remove(goodsId+ "");
                } else {
                    return R.error("购物车不存在当前商品");
                }

                if (objectMap.isEmpty()) {
                    JedisUtils.del(memberCartKey);
                    return R.ok("删除成功").put("totalFee", 0).put("l", resultList);
                }

                JedisUtils.setObjectMap(memberCartKey, objectMap, 0);
                Map<String, Object> map = JedisUtils.getObjectMap(memberCartKey);

                Map<String, Object> totalFeeAndGoods = getTotalFeeAndGoods(map, list, isMember);
                GoodsContentUtil.createContentBodyList(resultList, list, isMember);
                if ((int)totalFeeAndGoods.get("code") == 500) {
                    return R.error("商品信息错误");
                }
                BigDecimal beginMoney = (BigDecimal) totalFeeAndGoods.get("beginMoney");

                return R.ok("删除成功").put("beginMoney", beginMoney.doubleValue()).put("l", resultList).put("allNumber", totalFeeAndGoods.get("allNumber"));
            } else {
                return R.error("购物车不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("删除失败");
        }
    }

    /**
     *  http://localhost/f/orderAllController/showCartInfo
     * 展示购物车的信息
     * @param uid， 用户的id
     * @param request
     * @return
     */
    @RequestMapping("showCartInfo")
    public R showCartInfo(@RequestParam(value = "uid", defaultValue = "0")Long uid,
                          @RequestParam(value = "goodsId", defaultValue = "0")Long goodsId,
                          HttpServletRequest request) {

        if (uid == 0) {
            return R.error("参数错误");
        }
        R result = R.error();

        // 得到用户信息
        LvyouMember lvyouMember = lvyouMemberService.get(uid);
        if (lvyouMember == null) {
            return R.error("用户不存在");
        }
        String memberCartKey = DigestUtils.sha256Hex(lvyouMember.getMobile() + "qylyshop");
        List<GoodsContentVo> list = new ArrayList<>();

        boolean isMember = false;
//        if (nihaodamaMember.getState() == 1) {
//            isMember = true;
//        }

        // 判断是否存在，不存在就创建，存在就更新
        try {
            boolean exists = JedisUtils.exists(memberCartKey);
            if (exists) {

                // 判断此次的goodsid是否存在
                Map<String, Object> map = JedisUtils.getObjectMap(memberCartKey);



                if (map.isEmpty()) {
                    return R.ok().put("l", new ArrayList<>(0)).put("totalFee", 0).put("allNumber", 0).put("typeNumber", 0).put("goodsNumber", 0);
                }
                // 遍历map集合，然后从中取出商品的信息
                Map<String, Object> totalFeeAndGoods = getTotalFeeAndGoods(map, list, isMember);
//                if ((int)totalFeeAndGoods.get("code") == 500) {
//                    return R.error("商品不存在");
//                }


                // 进行contentBody的封装
                List<GoodsContentBodyVo> resultList = new ArrayList<>();
                GoodsContentUtil.createContentBodyList(resultList, list, isMember);


                Integer goodsNumber = 0;
                if (map.containsKey("" + goodsId)) {
                    goodsNumber = (Integer) map.get("" + goodsId);
                }

//                list.sort(new Comparator<GoodsContentVo>() {
//                    @Override
//                    public int compare(GoodsContentVo o1, GoodsContentVo o2) {
//                        if (o1.getGoodsId() == null || o2.getGoodsId() == null) {
//                            return 0;
//                        }
//                        return o1.getGoodsId().intValue() - o2.getGoodsId().intValue();
//
//                    }
//                });

//                if (isMember) {
//                    return R.ok().put("l", list).put("totalFee", totalFeeAndGoods.get("beginMoneyMember")).put("allNumber", totalFeeAndGoods.get("allNumber")).put("typeNumber", totalFeeAndGoods.get("typeNumber")).put("goodsNumber", goodsNumber);
//                } else {
//                    return R.ok().put("l", list).put("totalFee", totalFeeAndGoods.get("beginMoney")).put("allNumber", totalFeeAndGoods.get("allNumber")).put("typeNumber", totalFeeAndGoods.get("typeNumber")).put("goodsNumber", goodsNumber);
//                }

                String hint = null;
                if (totalFeeAndGoods.get("underReportory") != null) {
                    hint = "部分商品已超出库存最大值，已为您调整为最大库存";
                    JedisUtils.setObjectMap(memberCartKey, map, 0);
                }

                result = R.ok().put("l", resultList).put("totalFee", totalFeeAndGoods.get("beginMoney")).put("allNumber", totalFeeAndGoods.get("allNumber")).put("typeNumber", totalFeeAndGoods.get("typeNumber")).put("goodsNumber", goodsNumber).put("errHint", hint);
                return result;

            } else {

                result = R.ok().put("l", new ArrayList<>(0)).put("totalFee", 0).put("allNumber", 0).put("typeNumber", 0).put("goodsNumber", 0);
                return result;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败");
        }
    }


    /**
     *  http://localhost/f/orderAllController/clearShopCar
     * @param memberId
     * @return
     */
    @RequestMapping("clearShopCar")
    public R clearShopCar(@RequestParam(value = "uid",defaultValue = "0")Long memberId){
        if (memberId == 0) {
            return R.error("用户参数错误");
        }

        LvyouMember lvyouMember = lvyouMemberService.get(memberId);
        if(lvyouMember == null) {
            return R.error("用户参数错误");
        }

        String memberCartKey = DigestUtils.sha256Hex(lvyouMember.getMobile() + "qylyshop");
        Map<String, Object> map = JedisUtils.getObjectMap(memberCartKey);
        if (map == null) {
            return R.ok("您的购物车空空如也");
        }

        JedisUtils.del(memberCartKey);
        return R.ok("您的购物车空空如也");
    }

    /**
     * 展示用户要下的订单
     * http://localhost/f/orderAllController/showOrderInfo
     * @param uid
     * @param goodsIds
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("showOrderInfo")
    public R showOrderInfo(@RequestParam(value = "uid", defaultValue = "0")Long uid,
                              @RequestParam(value = "goodsIds", defaultValue = "[]")String goodsIds,
                              HttpServletRequest request,
                              HttpServletResponse response) {

        if (uid == 0) {
            return R.error("用户信息错误");
        }
        LvyouMember lvyouMember = lvyouMemberService.get(uid);

        if (lvyouMember == null) {
            return R.error("用户信息错误");
        }

        boolean isMember = false;

        Map<String, Object> redisCart = getRedisCart(lvyouMember);
        if (null == redisCart) {
            return R.error("您的购物车中没有商品了");
        }
        String[] ids = null;
        try {
             ids = JSON.parseObject(goodsIds, String[].class);
        }catch (Exception e) {
            e.printStackTrace();
            return R.error("参数错误");
        }

        if (ids.length == 0) {
            return R.error("请选择您的商品");
        }
        Set<String> idsSet = new HashSet<>();
        for (String one: ids) {
            if (!redisCart.containsKey(one)) {
                return R.error("商品信息错误");
            }
            idsSet.add(one);
        }

        List<LvyouSpecialtyProduct> fromMap = lvyouSpecialtyProductService.getFromMap(idsSet);

        if (idsSet.size() != ids.length) {
            return R.error("您的订单中有商品已下架");
        }

        for (LvyouSpecialtyProduct one: fromMap) {
            if (one.getReportory() < (Integer) redisCart.get(one.getId() + "")) {
                return R.error("部分商品库存不足");
            }
        }

        List<GoodsContentVo> resultContentList = new ArrayList<>();
        List<GoodsContentBodyVo> resultList = new ArrayList<>();

        GoodsContentUtil.createFromProduct(resultContentList, fromMap, redisCart);

        Map<String, Object> totalMap = GoodsContentUtil.createContentBodyList(resultList, resultContentList, isMember);

        return R.ok().put("l", resultList).put("totalFee", totalMap.get("totalFee"));

    }

    /**
     * 创建订单
     * http://localhost/f/orderAllController/createGoodsOrder
     * @param uid， 用户的id
     * @param harvestId， 收货地址的id
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("createGoodsOrder")
    public R createGoodsOrder(@RequestParam(value = "uid", defaultValue = "0")Long uid,
                              @RequestParam(value = "harvestId", defaultValue = "0")Long harvestId,
                              @RequestParam(value = "goodsIds", defaultValue = "[]")String goodsIds,
                              HttpServletRequest request,
                              HttpServletResponse response) {

        if (uid == 0) {
            return R.error("用户信息错误");
        }
        if (harvestId == 0) {
            return R.error("您还没有填收货地址哦");
        }

        // 得到用户的地址信息
        LvyouSpecialtyUserAddress lvyouSpecialtyUserAddress = lvyouSpecialtyUserAddressService.get(harvestId);

        LvyouMember lvyouMember = lvyouMemberService.get(uid);


        if (lvyouSpecialtyUserAddress == null) {
            return R.error("您还没有填收货地址哦");
        }
        boolean isMember = false;


        // 从redis中进行取数据

        Map<String, Object> redisCart = getRedisCart(lvyouMember);
        if (null == redisCart) {
            return R.error("您的购物车中没有商品了");
        }

        String[] ids = JSON.parseObject(goodsIds, String[].class);
        if (ids.length == 0) {
            return R.error("请选择您的商品");
        }

        Set<String> idsSet = new HashSet<>();
        for (String one: ids) {
            if (!redisCart.containsKey(one)) {
                return R.error("您的购物车中已不包含此商品，请返回购物车，重新添加");
            }
            idsSet.add(one);
        }

        List<LvyouSpecialtyProduct> checkProduct = lvyouSpecialtyProductService.getFromMap(idsSet);
        boolean kucunFlag = false;
        for (LvyouSpecialtyProduct one: checkProduct) {
            if ((Integer)redisCart.get(one.getId() + "") > one.getReportory()) {
                kucunFlag = true;
                return R.error("部分商品库存不足，请返回购物车中重新下单");
            }
        }
        if (kucunFlag) {
            JedisUtils.setObjectMap(DigestUtils.sha256Hex(lvyouMember.getMobile() + "qylyshop"), redisCart, 0);
            return R.error("商品库存不足");
        }

        GoodsOrderVo orderVo = lvyouSpecialtyOrderAllService.createOrder(redisCart, ids, lvyouMember, lvyouSpecialtyUserAddress, isMember, false);

        if (orderVo == null) {
            return R.error("创建订单失败");
        } else {
            amqpTemplate.convertAndSend("com.haojiangbo.topic", "goods.lxjlvyou.order", ObjectUtils.serialize(orderVo));

            // amqpTemplate.convertAndSend("com.haojiangbo.topic", "commodity.lxj.order", ObjectUtils.serialize(nihaodamaCommodityOrder));
            return R.ok().put("jsApi", createXiaoChengxuApi(orderVo, request)).put("goodsOrder", orderVo.getLvyouSpecialtyOrderAll().getOrderNo());

        }
    }

    @RequestMapping("cancelOrder")
    public R cancelOrder(@RequestParam(value = "contentOrderId", defaultValue = "0")Long contentOrderId,
                              HttpServletRequest request,
                              HttpServletResponse response) {

        if (contentOrderId == 0) {
            return R.error("订单信息错误");
        }

        LvyouSpecialtyOrderContent oneContent = lvyouSpecialtyOrderContentService.get(contentOrderId);
        if (oneContent == null) {
            return R.error("订单不存在");
        }
        List<LvyouSpecialtyOrderContent> contentList = lvyouSpecialtyOrderContentService.getByMerchantOrderNo(oneContent.getMerchantOrderNo());


        if (!(oneContent.getStatus() == OrderContentStatus.WZF.getStatus().intValue())) {
            return R.error("该订单不能取消");
        }

        LvyouSpecialtyOrderAll goodsOrder = lvyouSpecialtyOrderAllService.getByOrderNo(oneContent.getGoodsOrderNo());
        goodsOrder.setStatus(OrderContentStatus.YGQ.getStatus());
        if (lvyouSpecialtyOrderAllService.cancelOrder(goodsOrder, oneContent.getMerchantOrderNo()) == 0) {
            return R.error("订单取消失败");
        }

        return R.ok("订单已取消");
    }


    @RequestMapping("createGoodsOrderTwice")
    public R createGoodsOrderTwice(@RequestParam(value = "orderId", defaultValue = "0")Long orderId,
                                   HttpServletRequest request,
                                   HttpServletResponse response) {

        if (orderId == 0) {
            return R.error("订单信息错误");
        }

        LvyouSpecialtyOrderAll orderVo = lvyouSpecialtyOrderAllService.get(orderId);
        GoodsOrderVo goodsOrderVo = new GoodsOrderVo();
        orderVo.setOrderNo(SnowflakeIdWorker.getOrderNo("GOODSORDR"));
        goodsOrderVo.setLvyouSpecialtyOrderAll(orderVo);
        lvyouSpecialtyOrderAllService.save(orderVo);

        return R.ok().put("jsApi", createXiaoChengxuApi(goodsOrderVo, request)).put("goodsOrder", goodsOrderVo.getLvyouSpecialtyOrderAll().getOrderNo());
    }

    /**
     * 立即购买之前要调用的接口
     * http://localhost/f/orderAllController/buyAtOncePre
     * @param uid
     * @param goodsNumber
     * @param goodsId
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("buyAtOncePre")
    public R buyAtOncePre(@RequestParam(value = "uid", defaultValue = "0")Long uid,
                       @RequestParam(value = "goodsNumber", defaultValue = "0")Integer goodsNumber,
                       @RequestParam(value = "goodsId", defaultValue = "0")Long goodsId,
                       HttpServletRequest request,
                       HttpServletResponse response) {

        if (uid == 0) {
            return R.error("用户信息错误");
        }
        if (goodsNumber == 0) {
            return R.error("您没有选择相应的商品");
        }

        if (goodsId == 0) {
            return R.error("您还没有选择相应的商品");
        }

        // 得到用户和商品信息
        LvyouSpecialtyProduct lvyouSpecialtyProduct = lvyouSpecialtyProductService.get(goodsId);
        LvyouMember lvyouMember = lvyouMemberService.get(uid);

        if (lvyouSpecialtyProduct == null || lvyouMember == null){
            return R.error("参数错误！");
        }

        if (lvyouSpecialtyProduct.getReportory() < goodsNumber) {
            return R.error("商品库存不足");
        }

        boolean isMember = false;

        // 创建相应的body和相应的content
        List<GoodsContentBodyVo> bodyList = new ArrayList<>();
        List<GoodsContentVo> contentVoList = new ArrayList<>();
        // 组装成map
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put(goodsId+ "", goodsNumber);

        Map<String, Object> totalFeeAndGoodsMap = getTotalFeeAndGoods(paramMap, contentVoList, isMember);

        GoodsContentUtil.createContentBodyList(bodyList, contentVoList, isMember);

        return R.ok().put("bodyList", bodyList).put("realFee", totalFeeAndGoodsMap.get("realFee")).put("allNumber", totalFeeAndGoodsMap.get("allNumber")).put("freight", totalFeeAndGoodsMap.get("freight"));

    }

    /**
     * 立即购买按钮
     * http://localhost/f/orderAllController/buyAtOnce
     * @param uid
     * @param harvestId
     * @param goodsId
     * @param goodsNumber
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("buyAtOnce")
    public R buyAtOnce(@RequestParam(value = "uid", defaultValue = "0")Long uid,
                              @RequestParam(value = "harvestId", defaultValue = "0")Long harvestId,
                              @RequestParam(value = "goodsId", defaultValue = "0")Long goodsId,
                              @RequestParam(value = "goodsNumber", defaultValue = "0")Integer goodsNumber,
                              HttpServletRequest request,
                              HttpServletResponse response) {

        if (uid == 0) {
            return R.error("用户信息错误");
        }
        if (harvestId == 0) {
            return R.error("您还没有填收货地址哦");
        }

        if (goodsId == 0) {
            return R.error("您还没有选择相应的商品");
        }

        // 得到用户的地址信息
        LvyouSpecialtyUserAddress lvyouSpecialtyUserAddress = lvyouSpecialtyUserAddressService.get(harvestId);
        LvyouMember lvyouMember = lvyouMemberService.get(uid);

        if (lvyouSpecialtyUserAddress == null) {
            return R.error("您还没有填收货地址哦");
        }
        boolean isMember = false;

        LvyouSpecialtyProduct lvyouSpecialtyProduct = lvyouSpecialtyProductService.get(goodsId);
        if (lvyouSpecialtyProduct == null) {
            return R.error("商品信息错误");
        }

        if (lvyouSpecialtyProduct.getReportory() < goodsNumber) {
            return R.error("商品库存不足");
        }

        Map<String, Object> oneMap = new HashMap<>();
        oneMap.put(goodsId+"", goodsNumber);
        String[] ids = new String[1];
        ids[0] = goodsId + "";
        GoodsOrderVo orderVo = null;
        try {
             orderVo = lvyouSpecialtyOrderAllService.createOrder(oneMap, ids, lvyouMember, lvyouSpecialtyUserAddress, isMember, true);
        } catch (NoSuchMethodError e) {
            System.err.println("商品库存不足");
            return R.error("下单失败！订单中有部分商品库存不足");
        }


        if (orderVo == null) {
            return R.error("创建订单失败");
        } else {
            amqpTemplate.convertAndSend("com.haojiangbo.topic", "goods.lxjlvyou.order", ObjectUtils.serialize(orderVo));
            return R.ok().put("jsApi", createXiaoChengxuApi(orderVo, request)).put("goodsOrder", orderVo.getLvyouSpecialtyOrderAll().getOrderNo());

        }
    }

    /**
     * 展示用户的订单信息
     * http://localhost/f/orderAllController/getMemberGoodsOrder
     * @param uid
     * @param request
     * @return
     */
    @RequestMapping("getMemberGoodsOrder")
    public R getMemberGoodsOrder(@RequestParam(value = "uid", defaultValue = "0")Long uid,
                                 @RequestParam(value = "pageNo", defaultValue = "1")Integer pageNo,
                                 @RequestParam(value = "pageSize", defaultValue = "15")Integer pageSize,
                                 @RequestParam(value = "status", defaultValue = "")String status,
                                 HttpServletRequest request) {
        if (uid == 0 || pageNo < 1) {
            return R.error("参数错误");
        }

        Map<String, Object> param = getPageNo(pageNo, pageSize);
        param.put("userId", uid);

        if (StringUtils.isEmpty(status)) {
            return R.error("参数错误");
        }

        List<String> statusList = new ArrayList<>();
        statusList.add("");
        statusList.add("0");
        statusList.add("2");
        statusList.add("3");

        if (!statusList.contains(status)) {
            return R.error("状态值出错");
        }

        if (!StringUtils.equals("0", status)) {
            param.put("statusAll", 2);
        } else {
            param.put("statusAll", 1);
        }

        List<GoodsOrderVo> resultList = new ArrayList<>();
        List<LvyouSpecialtyOrderAll> list = lvyouSpecialtyOrderAllService.list(param);


        for (LvyouSpecialtyOrderAll oneOrder : list) {
            GoodsOrderVo orderVo = new GoodsOrderVo();
            orderVo.setLvyouSpecialtyOrderAll(oneOrder);

            List<LvyouSpecialtyOrderContent> ordercontentList = lvyouSpecialtyOrderContentService.getByOrderNo(oneOrder.getOrderNo());

            List<LvyouSpecialtyOrderContent> delList = new ArrayList<>();
            for (LvyouSpecialtyOrderContent one : ordercontentList) {
                if (!(StringUtils.isEmpty(status) || StringUtils.equals("0", status))) {
                    if (!StringUtils.equals(status, one.getStatus() + "")) {
                        delList.add(one);
                    }
                }
            }

            ordercontentList.removeAll(delList);
            List<GoodsContentBodyVo> resultList2 = new ArrayList<>();
            GoodsContentUtil.createContentBodyListFrom(resultList2, ordercontentList);

            orderVo.setList(resultList2);
            resultList.add(orderVo);
        }

        return R.ok().put("l", resultList);

    }


    /**
     * 查看单个的订单
     * http://localhost/f/orderAllController/getOneMemberGoodsOrder
     * @param goodsOrderId
     * @param uid
     * @param request
     * @return
     */
    @RequestMapping("getOneMemberGoodsOrder")
    public R getOneMemberGoodsOrder(@RequestParam(value = "orderId", defaultValue = "0")Long goodsOrderId,
                                    @RequestParam(value = "uid", defaultValue = "0")Long uid,
                                    @RequestParam(value = "merchantId", defaultValue = "0")Long merchantId,
                                    HttpServletRequest request) {
        if (goodsOrderId == 0 || uid == 0 ||merchantId == 0) {
            return R.error("参数错误");
        }

        // 查询订单信息
        LvyouSpecialtyOrderAll lvyouSpecialtyOrderAll = lvyouSpecialtyOrderAllService.get(goodsOrderId);
        if (lvyouSpecialtyOrderAll == null || lvyouSpecialtyOrderAll.getStatus() == 3) {
            return R.error("不存在该订单");
        }

        if (lvyouSpecialtyOrderAll.getUserId().longValue() != uid) {
            return R.error("用户不匹配");
        }

//        LvyouSpecialtyUserAddress address = lvyouSpecialtyUserAddressService.get(lvyouSpecialtyOrderAll.getUserAddressId());

        List<LvyouSpecialtyOrderContent> ordercontentList = lvyouSpecialtyOrderContentService.getByOrderNoAndMerchant(lvyouSpecialtyOrderAll.getOrderNo(), merchantId);


        GoodsOrderVo orderVo = new GoodsOrderVo();

        LvyouSpecialtyUserAddress address = new LvyouSpecialtyUserAddress();
        if (ordercontentList.size() > 0) {
            LvyouSpecialtyOrderContent lvyouSpecialtyOrderContent = ordercontentList.get(0);
            address.setReceiverName(lvyouSpecialtyOrderContent.getUserUname());
            address.setReceiverAddress(lvyouSpecialtyOrderContent.getUserAddressName());
            address.setReceiverCitys(lvyouSpecialtyOrderContent.getReceiverCitys());
            address.setReceiverMobile(lvyouSpecialtyOrderContent.getUserMobile());
        }

        orderVo.setLvyouSpecialtyUserAddress(address);
        orderVo.setLvyouSpecialtyOrderAll(lvyouSpecialtyOrderAll);


//        Map<String, Object> resultMap = createContentList(list, ordercontentList, 0);
//        BigDecimal beginMoney = (BigDecimal) resultMap.get("beginMoney");
//        BigDecimal beginMoneyMember = (BigDecimal) resultMap.get("beginMoneyMember");
//        if (nihaodamaYouxuanGoodsOrder.getMstate() == 0) {
//            totalFeePay = beginMoney;
//        } else {
//            totalFeePay = beginMoneyMember;
//            minus = CurrencyUtils.minus(beginMoney, beginMoneyMember);
//        }
        List<GoodsContentBodyVo> resultBodyList = new ArrayList<>();
        GoodsContentUtil.createContentBodyListFrom(resultBodyList, ordercontentList);

        orderVo.setList(resultBodyList);

        return R.ok().put("i", orderVo);
    }


    /************************************************得到用户的购物车***************************************************************/
    private Map<String, Object> getRedisCart(LvyouMember lvyouMember) {
        String memberCartKey = DigestUtils.sha256Hex(lvyouMember.getMobile() + "qylyshop");
        return JedisUtils.getObjectMap(memberCartKey);
    }


    /******************************************进行计算商品的总价,并返回商品的详细信息**********************************************************/
    /**
     * map中有三个值：总价 beginMoney，运费 freight，会员总价 beginMoneyMember
     * @param map
     * @param list
     * @param isMember
     * @return
     */
    private Map<String, Object> getTotalFeeAndGoods(Map<String, Object> map, List<GoodsContentVo> list, boolean isMember) {
        Map<String, Object> result = new HashMap<>();
//        BigDecimal freight = new BigDecimal(0);
        Double freight = 0D;
        BigDecimal beginMoney = new BigDecimal(0);
        BigDecimal beginMoneyMember = new BigDecimal(0);

        Integer allNumber = 0;



        Set<Map.Entry<String, Object>> entries = map.entrySet();
        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();

        // 得到map中的商品信息
        Map<String, LvyouSpecialtyProduct> goodsMap = new HashMap<>();
        List<LvyouSpecialtyProduct> fromMap = lvyouSpecialtyProductService.getFromMap(map.keySet());

        for (LvyouSpecialtyProduct one: fromMap) {
            goodsMap.put(one.getId() + "", one);
        }

        Map<String, Integer> changeMap = new HashMap<>();

        while (iterator.hasNext()) {
            GoodsContentVo goodsContentVo = new GoodsContentVo();
            Map.Entry<String, Object> next = iterator.next();
            // LvyouSpecialtyProduct lvyouSpecialtyProduct = lvyouSpecialtyProductService.get(Long.parseLong(next.getKey()));

            if (!goodsMap.containsKey(next.getKey())) {
                goodsContentVo.setGoodsStatus(1);
                list.add(goodsContentVo);
                continue;
            }

            LvyouSpecialtyProduct lvyouSpecialtyProduct = goodsMap.get(next.getKey());

            goodsContentVo.setGoodsId(lvyouSpecialtyProduct.getId());
            goodsContentVo.setGoodsName(lvyouSpecialtyProduct.getName());
            // String[] images = JSON.parseObject(lvyouSpecialtyProduct.getImages(), String[].class);
            goodsContentVo.setGoodsImage(lvyouSpecialtyProduct.getCover());
            goodsContentVo.setGoodsHprice(lvyouSpecialtyProduct.getHprice());
            goodsContentVo.setMerchantName(lvyouSpecialtyProduct.getMerchantName());
            goodsContentVo.setMerchantId(lvyouSpecialtyProduct.getMerchantId());
            Integer numberInRedis = (Integer) next.getValue();
            if (lvyouSpecialtyProduct.getReportory() >= numberInRedis) {
                goodsContentVo.setGoodsNumber(numberInRedis);
            } else {
                goodsContentVo.setGoodsStatus(3);
                result.put("underReportory", 1);
                if (lvyouSpecialtyProduct.getReportory() == 0) {
                    continue;
                } else {
                    goodsContentVo.setGoodsNumber(lvyouSpecialtyProduct.getReportory());
                }
                changeMap.put(next.getKey(), lvyouSpecialtyProduct.getReportory());
            }


            goodsContentVo.setGoodsStatus(0);
            goodsContentVo.setFreight(lvyouSpecialtyProduct.getFreight());


            Double goodFreight = lvyouSpecialtyProduct.getFreight();
//            if (goodFreight > freight) {
//                freight = goodFreight;
//            }

            if (goodFreight > freight) {
                freight = goodFreight;
            }
            BigDecimal multiply = CurrencyUtils.multiply(new BigDecimal(lvyouSpecialtyProduct.getPrice()), new BigDecimal((Integer) next.getValue()));
            BigDecimal multiplyMember = CurrencyUtils.multiply(new BigDecimal(lvyouSpecialtyProduct.getHprice()), new BigDecimal((Integer) next.getValue()));

            beginMoneyMember = CurrencyUtils.add(beginMoneyMember, multiplyMember);

            beginMoney = CurrencyUtils.add(beginMoney, multiply);

            allNumber += (Integer) next.getValue();
            if (isMember) {
                goodsContentVo.setGoodsFee(multiplyMember.doubleValue());
                goodsContentVo.setGoodsPrice(lvyouSpecialtyProduct.getHprice());
            } else {
                goodsContentVo.setGoodsFee(multiply.doubleValue());
                goodsContentVo.setGoodsPrice(lvyouSpecialtyProduct.getPrice());
            }

            list.add(goodsContentVo);
        }

        for (Map.Entry one: changeMap.entrySet()) {
            if ((Integer)one.getValue() == 0) {
                map.remove(one.getKey());
            } else {
                map.put((String) one.getKey(), one.getValue());
            }

        }

        BigDecimal realFee = CurrencyUtils.add(beginMoney, new BigDecimal(freight));

        result.put("code", 0);
        result.put("beginMoney", beginMoney);
        result.put("freight", freight);
        result.put("beginMoneyMember", beginMoneyMember);
        result.put("allNumber", allNumber);
        result.put("typeNumber", list.size());
        result.put("realFee", realFee);
        return result;
    }



    /**************************************微信支付签名  回调   start*************************************************/

    Map createXiaoChengxuApi(GoodsOrderVo orderVo, HttpServletRequest request){
        //随机字符串
        LvyouSpecialtyOrderAll order = orderVo.getLvyouSpecialtyOrderAll();
        String nonce_str = CommonUtil.CreateNoncestr();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + request.getContextPath();
        WxPayHelper wxPayHelper = new WxPayHelper();
        /*新的商户信息*/
        wxPayHelper.setApiKey(xcxConfigService.getDefalt().getApiKey());
        //小程序id
        wxPayHelper.setAppId(xcxConfigService.getDefalt().getAppId());
        //商户号
        wxPayHelper.setMchId(xcxConfigService.getDefalt().getMemchantNo());

        wxPayHelper.SetParameter("openid",order.getUserOpenId());
        //商品描述
        wxPayHelper.SetParameter("body", "特产商城商品"+order.getMoney()+"元");
        wxPayHelper.SetParameter("nonce_str", nonce_str);
        //通知地址
        wxPayHelper.SetParameter("notify_url", basePath
                + "/f/orderAllController/wxCallBackXiao");
        wxPayHelper.SetParameter("out_trade_no", order.getOrderNo());
        //标价金额
        wxPayHelper.SetParameter("total_fee", String.format("%.0f",order.getMoney()*100));
        //终端IP
        wxPayHelper.SetParameter("spbill_create_ip",
                IPUtils.getIpAddr(request));
        //交易类型
        wxPayHelper.SetParameter("trade_type", "JSAPI");
        wxPayHelper.SetParameter("attach", "特产商城");
        try {
            Map m = wxPayHelper.createPayByJSAPI(xcxConfigService.getDefalt().getAppId());
            return  m;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Map<String, String> createWxPay(GoodsOrderVo orderVo, HttpServletRequest request, HttpServletResponse response) {
        String params = "";
        try {
            LvyouSpecialtyOrderAll order = orderVo.getLvyouSpecialtyOrderAll();
            String orderNo = order.getOrderNo();
            Double totalPrice = order.getMoney();

            String nonce_str = CommonUtil.CreateNoncestr();
            String basePath =  request.getScheme() + "://"
                    + request.getServerName() + request.getContextPath();
            WxPayHelper wxPayHelper = new WxPayHelper();
            wxPayHelper.setApiKey(PayPar.appkey);
            wxPayHelper.setAppId(PayPar.appId);
            wxPayHelper.setMchId(PayPar.mchId);
            wxPayHelper.SetParameter("body", "购买"+"特产商城商品");
            wxPayHelper.SetParameter("nonce_str", nonce_str);
            wxPayHelper.SetParameter("notify_url", basePath
                    + "/f/orderAllController/wxCallBack");

            wxPayHelper.SetParameter("out_trade_no", orderNo);

            wxPayHelper.SetParameter("total_fee",String.format("%.0f",totalPrice*100));

            wxPayHelper.SetParameter("spbill_create_ip",
                    IPUtils.getIpAddr(request));

            wxPayHelper.SetParameter("trade_type", "APP");
            wxPayHelper.SetParameter("attach", "微信支付");

            return wxPayHelper.createAppPay();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * http://127.0.0.1/f/orderAllController/wxCallBack/
     * @return
     * @throws Exception
     */
    @RequestMapping("wxCallBack")
    //@ResponseBody
    public void wxCallBack(HttpServletRequest request,HttpServletResponse response) throws Exception {
        if(wxCallBackHander(request, response)) {
            if(null != response.getWriter()) {
                response.getWriter().println(WXPAYOK);
            }
        }else {
            if(null != response.getWriter()) {
                response.getWriter().println(WXPAYNO);
            }
        }
        if(null != response.getWriter()) {
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    /**
     *    * http://127.0.0.1/f/orderAllController/wxCallBackXiao
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("wxCallBackXiao")
    //@ResponseBody
    public void wxCallBackXiao(HttpServletRequest request,HttpServletResponse response) throws Exception {
        if(wxCallBackXiaoHander(request, response)) {
            if(null != response.getWriter()) {
                response.getWriter().println(WXPAYOK);
            }
        }else {
            if(null != response.getWriter()) {
                response.getWriter().println(WXPAYNO);
            }
        }
        if(null != response.getWriter()) {
            response.getWriter().flush();
            response.getWriter().close();
        }
    }

    // 测试回调
    // http://localhost/f/orderAllController/wxCallBack/
    @RequestMapping("wxCallBackCeshi")
    //@ResponseBody
    public R wxCallBackCeshi(HttpServletRequest request,HttpServletResponse response, @RequestParam("orderNo")String orderNo) throws Exception {
        LvyouSpecialtyOrderAll goodsOrder =  lvyouSpecialtyOrderAllService.getByOrderNo(orderNo);
        if(null != goodsOrder){

            if(goodsOrder.getStatus() != 2){

                goodsOrder.setStatus(2);
                goodsOrder.setWxOrderNo("123");
                int result = lvyouSpecialtyOrderAllService.wxBackGoodsNumber(goodsOrder);

                if (result == 0) {
                    return R.error();
                } else {
//                    String memberCartKey = DigestUtils.sha256Hex(goodsOrder.getUserMobile() + "qylyshop");
//                    JedisUtils.del(memberCartKey);
                    return R.ok();
                }
            }
            return R.error();
        }
        return R.error();
    }


    /**
     * 回掉处理防止并发
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    synchronized  boolean  wxCallBackHander(HttpServletRequest request,HttpServletResponse response) throws Exception {

        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bReader = request.getReader();
        String line = "";
        while ((line = bReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        if (StringUtils.isEmpty(stringBuffer.toString())) {
            return false;
        }
        System.out.println("微信回调参数-------------------" + stringBuffer.toString());
        Map<String, String> xmlMap = XMLUtils.xml2Map(stringBuffer.toString());

        String resXml = null;
        if ("SUCCESS".equals(xmlMap.get("xml.result_code"))) {
            String out_trade_no = xmlMap.get("xml.out_trade_no");
            String total_fee = xmlMap.get("xml.total_fee");
            String transaction_id = xmlMap.get("xml.transaction_id");
            Hog.e("支付回调 时间 = {}，订单号 = {}，微信单号 ={}",
                    DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), out_trade_no, transaction_id);
            if (com.alibaba.druid.util.StringUtils.isEmpty(transaction_id)
                    || com.alibaba.druid.util.StringUtils.isEmpty(total_fee) ||
                    StringUtils.isEmpty(out_trade_no)
            ) {
                return false;
            }

            /**
             * 支付回调参数验证  防止别人恶意篡改回调数据
             */
            if (!PayCheckSginUtils.checkWxSgin(xmlMap, PayPar.appkey)) {
                return false;
            }
            /*  YuyueOrder yuyueOrder = yuyueOrderService.getByOrderNo(out_trade_no);*/
            LvyouSpecialtyOrderAll goodsOrder =  lvyouSpecialtyOrderAllService.getByOrderNo(out_trade_no);
            if(null != goodsOrder){

                if(goodsOrder.getStatus() != OrderContentStatus.YZFW.getStatus().intValue()){

                    goodsOrder.setStatus(OrderContentStatus.YZFW.getStatus());
                    goodsOrder.setWxOrderNo(transaction_id);
                    int result = lvyouSpecialtyOrderAllService.wxBackGoodsNumber(goodsOrder);

                    if (result == 0) {
                        return false;
                    } else {
                        String memberCartKey = DigestUtils.sha256Hex(goodsOrder.getUserMobile() + "qylyshop");
                        JedisUtils.del(memberCartKey);
                        return true;
                    }
                }
                return true;
            }
        }
        return  false;
    }

    /**
     * 回掉处理防止并发
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    synchronized  boolean  wxCallBackXiaoHander(HttpServletRequest request, HttpServletResponse response) throws Exception {

        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bReader = request.getReader();
        String line = "";
        while ((line = bReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        Map<String, String> xmlMap = XMLUtils.xml2Map(stringBuffer.toString());
        System.err.println("微信回调参数-------------------" + stringBuffer.toString());
        String resXml = null;
        if ("SUCCESS".equals(xmlMap.get("xml.result_code"))) {
            String out_trade_no = xmlMap.get("xml.out_trade_no");
            String total_fee = xmlMap.get("xml.total_fee");
            String transaction_id = xmlMap.get("xml.transaction_id");
            Hog.e("支付回调 时间 = {}，订单号 = {}，微信单号 ={}",
                    DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), out_trade_no, transaction_id);
            if (com.alibaba.druid.util.StringUtils.isEmpty(transaction_id)
                    || com.alibaba.druid.util.StringUtils.isEmpty(total_fee) ||
                    StringUtils.isEmpty(out_trade_no)
            ) {
                return false;
            }
            /**
             * 支付回调参数验证  防止别人恶意篡改回调数据
             */
            if (!PayCheckSginUtils.checkWxSgin(xmlMap, xcxConfigService.getDefalt().getApiKey())) {
                return false;
            }

            LvyouSpecialtyOrderAll goodsOrder =  lvyouSpecialtyOrderAllService.getByOrderNo(out_trade_no);
            if(null != goodsOrder){

                if(goodsOrder.getStatus() != OrderContentStatus.YZFW.getStatus().intValue()){

                    List<LvyouSpecialtyOrderContent> byOrderNo = lvyouSpecialtyOrderContentService.getByOrderNo(out_trade_no);
//                    Config config = new Config();
                    LvyouSpecialtyGzhConfig defalt = lvyouSpecialtyGzhConfigService.getDefault();
//                    config.setWxAppId(defalt.getAppId());
//                    config.setWxAppSecret(defalt.getAppsecret());
                    Config config = configService.getByUserId(1L);
                    for (LvyouSpecialtyOrderContent one: byOrderNo) {
                        UserDO userDO = userService.getByMerchantId(one.getMerchantId());

                        SendMbMessageUtils.sendUserDefaultTempMessage(userDO, config, defalt.getMessageRedirectUrl());
                    }

                    goodsOrder.setStatus(OrderContentStatus.YZFW.getStatus());
                    goodsOrder.setWxOrderNo(transaction_id);
                    // int result = lvyouSpecialtyOrderAllService.wxBackGoodsNumber(goodsOrder);

                    int result = lvyouSpecialtyOrderAllService.wxBackSstatus(goodsOrder);

                    if (result == 0) {
                        return false;
                    }
                    return true;
//                    } else {
//                        String memberCartKey = DigestUtils.sha256Hex(goodsOrder.getUserMobile() + "qylyshop");
//                        JedisUtils.del(memberCartKey);
//                        return true;
//                    }
                }
                return true;
            }

//            int r =  lvyouScenicTicketOrderService.updateStatusByOrderNo(2, out_trade_no,1,transaction_id,null);
//            if(r <= 0){
//                return false;
//            }
            //状态修改成功之后的操作
            return false;
        }
        return  false;
    }


    /**
     * 创建一个map来存储单子中所有单独商品的信息，此方法在进行购物车计算以及进行订单的展示时候进行使用
     * @param list
     * @param orderList
     * @param isMember
     * @return
     */
    public Map<String, Object> createContentList(List<GoodsContentVo> list, List<LvyouSpecialtyOrderContent> orderList, Integer isMember) {

        Map<String, Object> result = new HashMap<>();


        for (LvyouSpecialtyOrderContent order  : orderList) {

            GoodsContentVo orderVo = new GoodsContentVo();
            orderVo.setGoodsId(order.getGoodsId());

            orderVo.setGoodsImage(order.getGoodsImages());
            orderVo.setGoodsNumber(order.getGoodsNumber());
            orderVo.setGoodsName(order.getGoodsName());
            orderVo.setGoodsFee(order.getGoodsFee());
            orderVo.setMerchantId(order.getMerchantId());
            orderVo.setMerchantName(order.getMerchantName());
            orderVo.setGoodsStatus(0);

            if (isMember == 0) {
                orderVo.setGoodsPrice(order.getGoodsPrice());
            } else {
                orderVo.setGoodsPrice(order.getGoodsHprice());
            }

            list.add(orderVo);
        }

        return result;
    }

    private boolean testReportory(LvyouSpecialtyProduct lvyouSpecialtyProduct, Integer number) {

        if (lvyouSpecialtyProduct.getReportory() < number) {
            return false;
        }
        return true;
    }

    /**
     * http://127.0.0.1/f/orderAllController/create_tk_order
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping("/create_tk_order")
    public R createTkOrder(
            @RequestParam("contentId") Long contentId,
            HttpServletRequest request,HttpServletResponse response){
        LvyouSpecialtyOrderContent lvyouSpecialtyOrderContent = lvyouSpecialtyOrderContentService.get(contentId);
        if (lvyouSpecialtyOrderContent == null) {
            return R.error("该订单不存在");
        }
        String merchantOrder = lvyouSpecialtyOrderContent.getMerchantOrderNo();

        LvyouSpecialtyOrderAll byOrderNo = lvyouSpecialtyOrderAllService.getByOrderNo(lvyouSpecialtyOrderContent.getGoodsOrderNo());

        List<LvyouSpecialtyOrderContent> lvyouSpecialtyOrderContents = lvyouSpecialtyOrderContentService.getByMerchantOrderNo(merchantOrder);
        if (lvyouSpecialtyOrderContents.size() == 0) {
            return R.error("订单信息错误");
        }

        TuikuanVo tuikuanVo = new TuikuanVo();

        tuikuanVo.setOrderNo(lvyouSpecialtyOrderContents.get(0).getWxOrderNo());
        tuikuanVo.setMerchantId(lvyouSpecialtyOrderContents.get(0).getMerchantId());
        tuikuanVo.setUserOpenId(lvyouSpecialtyOrderContents.get(0).getUserOpenId());
        tuikuanVo.setMerchantOrderNo(lvyouSpecialtyOrderContent.getMerchantOrderNo());
        tuikuanVo.setAllMoney(byOrderNo.getMoney());
        for (LvyouSpecialtyOrderContent one: lvyouSpecialtyOrderContents) {
            if (one.getStatus() != OrderContentStatus.YZFW.getStatus().intValue()) {
                return R.error("该订单不允许退款");
            } else {
                BigDecimal goodsFee = CurrencyUtils.add(new BigDecimal(tuikuanVo.getMoney()), new BigDecimal(one.getGoodsFee()));
                BigDecimal allFee = CurrencyUtils.add(goodsFee, new BigDecimal(one.getFreight()));
                tuikuanVo.setMoney(allFee.doubleValue());
            }
        }

        int tuikuanOrder = lvyouSpecialtyOrderAllService.createTuikuanOrder(merchantOrder);
        if (tuikuanOrder == 0) {
            return R.error("申请退款失败");
        }

        try {
            String r =  createTuikuanPar(tuikuanVo,request);
            Hog.e("退款参=={}",r);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("退款申请失败");
        }
//        String tkOrderNo = SnowflakeIdWorker.getOrderNo("TK");
//        if (lvyouSpecialtyOrderContentService.tkOrderNo(merchantOrder, tkOrderNo, OrderContentStatus.TF.getStatus()) == 0) {
//            return R.error("退款申请失败");
//        }
        return R.ok("您的退款已提交申请,请耐心等待");
    }

//    @RequestMapping("changeWxOrderNo")
//    public R change() {
//
//        List<LvyouSpecialtyOrderAll> list = lvyouSpecialtyOrderAllService.list(new HashMap<>());
//        for (LvyouSpecialtyOrderAll one : list) {
//            if (one.getWxOrderNo() != null) {
//                lvyouSpecialtyOrderContentService.updateStatus(one.getOrderNo(), one.getWxOrderNo());
//            }
//        }
//        return R.ok();
//    }


    /**
     * 创建退款js
     * @param order
     * @return
     * @throws Exception
     */
    String createTuikuanPar(TuikuanVo order,HttpServletRequest request) throws Exception{
        XcxConfig xcxConfig =  xcxConfigService.getDefalt();
        String nonce_str = CommonUtil.CreateNoncestr();
        String basePath = request.getScheme() + "://"
                + request.getServerName() + request.getContextPath();
        WxPayHelper wxPayHelper = new WxPayHelper();
        Map map = new HashMap();
        map.put("appid", xcxConfig.getAppId());
        map.put("mch_id", xcxConfig.getMemchantNo());
        map.put("nonce_str", nonce_str);
        map.put("notify_url", basePath
                + "/f/orderAllController/wxTuikuanCallBack");
        map.put("transaction_id",order.getOrderNo());
        String tkOrder = SnowflakeIdWorker.getOrderNo("TK");

        if (lvyouSpecialtyOrderContentService.tkPre(order.getMerchantOrderNo(), tkOrder) == 0) {
            throw new Exception("数据库保存失败");
        }
        map.put("out_refund_no", tkOrder);
        map.put("total_fee", String.format("%.0f",order.getAllMoney()*100));
        map.put("refund_fee", String.format("%.0f",order.getMoney()*100));
        map.put("sign", MoneyUtils.createSign(map, xcxConfig.getApiKey()));// 签名
        return TuikuanUtils.createTuikuan(map, xcxConfig.getMemchantNo(), xcxConfig.getBookPath());
    }



    @RequestMapping("/wxTuikuanCallBack")
    public void wxTkCallbanck(HttpServletRequest request,HttpServletResponse response) throws Exception {
        if(wxTuikuanCallBackHander(request, response)) {
            if(null != response.getWriter()) {
                response.getWriter().println(WXPAYOK);
            }
        }else {
            if(null != response.getWriter()) {
                response.getWriter().println(WXPAYNO);
            }
        }
        if(null != response.getWriter()) {
            response.getWriter().flush();
            response.getWriter().close();
        }
    }


    /**
     * 回掉处理防止并发
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    synchronized  boolean  wxTuikuanCallBackHander(HttpServletRequest request,HttpServletResponse response) throws Exception{

        StringBuffer stringBuffer = new StringBuffer();
        BufferedReader bReader = request.getReader();
        String line = "";
        while ((line = bReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        Map<String, String> xmlMap = XMLUtils.xml2Map(stringBuffer.toString());
        System.err.println("微信退款回调参数-------------------"+stringBuffer.toString());
        String resXml = null;
        if ("SUCCESS".equals(xmlMap.get("xml.return_code"))) {
            if(xmlMap.containsKey("xml.req_info")) {
                String req_info = xmlMap.get("xml.req_info");
                String jiemi =  AESUtils.decryptData(req_info, xcxConfigService.getDefalt().getApiKey());
                Hog.e("退款回调解密后的参数 = {}",jiemi);
                if(!StringUtils.isEmpty(jiemi)) {
                    Map<String, String> xmlMap2 = XMLUtils.xml2Map(jiemi);
                    if("SUCCESS".equals(xmlMap2.get("root.refund_status"))) {
                        if(StringUtils.isEmpty(xmlMap2.get("root.out_trade_no").toString())){
                            return false;
                        }
                        try {
                            int r = lvyouSpecialtyOrderContentService.tkBackChangeNumber(xmlMap2.get("root.out_refund_no"), xmlMap2.get("root.refund_id"), OrderContentStatus.YTK.getStatus());
                            if(r > 0){
                                return true;
                            }
                        } catch (Exception e) {
                            return false;
                        }

                    }
                }

            }
            return true;
        }
        return false;

    }

}
